﻿package com.cilico.single.components;


import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.DateKeyListener;
import android.text.method.DialerKeyListener;
import android.text.method.DigitsKeyListener;
import android.text.method.NumberKeyListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cilico.single.ConfigManager;
import com.cilico.single.R;
import com.cilico.single.utils.ConstantRepository;
import com.cilico.single.utils.Utils;
import com.cilico.single.view.BaseView;
import com.cilico.single.view.FormLayout;

public class mTextField extends EditText implements Component {

	public CssStyle cssStyle_;
	/**
	 * Indicator of setting label and input field in ONE row.
	 */
	boolean isLabelIndianFile_;

	/**
	 * Indicate the inputting is not empty.
	 */
	public boolean required_;
	public boolean mask_;

	public int inputFieldWidth_;

	/**
	 * minimum of the characters
	 */
	public int minSize_;
	int maxSize_;
	// 输入框的输入限制类型
	private int inputType_;
	/* input not support "." */
	Paint form_;

	public String attrName_;
	public String attrValue_;
	public String attrTrueValue_;
	public boolean attrSave_;
	public boolean attrTrueSave_;
	public String isEncrypt_;
	public String tableName_;
	// 输入框类型
	public String textFieldType_;
	// 是否加减联动
    public String isLinked_;
    // 输入框最大值
    public int maxValue_ = 999;
    // 输入框最小值
    public int minValue_ = 0;
	private int height_;
	int width_;
	BaseView bv_;
	public boolean saveHistory_;
	boolean isComlexbobox_ = false;
	boolean isDeletel_= true;
	boolean isSingleChoice_ ;
	boolean isSearch_ = false;
	public static mTextField staticTextField_; 
	public Select comboboxSelect_;
	static Bitmap comboboxImg_ = null;
	public static Bitmap deletelImg_ = null;
	private Paint paint_;
	String stlye = "num";
	int index;
	int scrollUpDistance_ = 0;
	int currentScrollY_ = 0;
	boolean showAtLocation;
	
    // 一键清除按钮
    static Drawable drawable;
    
    // 输入框是否处于激活状态。
    String isEnable_ = "";
	
	/**
	 * Creates a new TextField object with the given label, initial contents, maximum size in characters, and
	 * constraints. If the text parameter is null, the TextField is created empty. The maxSize parameter must be
	 * greater than zero. An IllegalArgumentException is thrown if the length of the initial contents string exceeds
	 * maxSize. However, the implementation may assign a maximum size smaller than the application had requested. If
	 * this occurs, and if the length of the contents exceeds the newly assigned maximum size, the contents are
	 * truncated from the end in order to fit, and no exception is thrown.
	 * 
	 * @param label
	 *            item label
	 * @param text
	 *            the initial contents, or null if the TextField is to be empty
	 * @param maxSize
	 *            the maximum capacity in characters
	 * @param constraints
	 *            see {@link javax.microedition.lcdui.TextField} input constraints
	 * @throws IllegalArgumentException
	 *             if maxSize is zero or less
	 * @throws IllegalArgumentException
	 *             if the value of the constraints parameter is invalid
	 * @throws IllegalArgumentException
	 *             if text is illegal for the specified constraints
	 * @throws IllegalArgumentException
	 *             if the length of the string exceeds the requested maximum capacity
	 */
	public mTextField(Context context, String label, String text, String hint, boolean required, int maxSize, int minSize, int constraints, boolean disable) {
		super(context);
		bv_ = (BaseView) context;
		// TODO Auto-generated constructor stub
		this.setText(text);
		// 设置控件字符最大输入量
		this.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxSize) });
		maxSize_ = maxSize;
		this.minSize_ = minSize;
		this.setFocusable(true);
		setEnabled(disable);
		inputType_ = constraints;
//		this.setPadding(5, 0, 35, 0);
		this.addTextChangedListener(new TextDefine());
		// 设置输入框的提示语言
		if (null != hint)
			this.setHint(hint);
		switch (constraints) {
		case ConfigManager.InputType_DECIMAL:
			setKeyListener(new NumberKeyListener() {
				protected char[] getAcceptedChars() {
					return new char[] {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '.'};
				}
				public int getInputType() {
					if ("samsung".equalsIgnoreCase(android.os.Build.BRAND)) { 
						// 三星GT-N7000 GT-N7100的InputType.TYPE_CLASS_PHONE软键盘没有小数点
						return InputType.TYPE_CLASS_TEXT;
					}
					return InputType.TYPE_CLASS_PHONE;
				}
			});
			break;
			
		case ConfigManager.InputType_PLUS_DIGIT: // 正整数："0-9"
			setKeyListener(new NumberKeyListener() {
                protected char[] getAcceptedChars() {
                    return new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
                }

                public int getInputType() {
                    return InputType.TYPE_CLASS_PHONE;
                }
            });
			
		case ConfigManager.InputType_PLUS_DECIMAL: // 正小数:只接受"0-9"、和"."
			setKeyListener(new NumberKeyListener() {
                protected char[] getAcceptedChars() {
                    return new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
                }

                public int getInputType() {
                    if ("samsung".equalsIgnoreCase(android.os.Build.BRAND)||"Xiaomi".equalsIgnoreCase(android.os.Build.BRAND) ) { 
                        //特殊处理：三星手机TYPE_CLASS_PHONE没有小数点
                        return InputType.TYPE_CLASS_TEXT;
                    }
                    return InputType.TYPE_CLASS_PHONE;
                }
            });
			break;	
			
		case ConfigManager.InputType_NUMBER:
			setKeyListener(new DigitsKeyListener(true, false));
			break;
		case ConfigManager.InputType_DATETIME:
			setKeyListener(new DateKeyListener());
			break;
		case ConfigManager.InputType_PHONE:
			setKeyListener(new DialerKeyListener());
			break;
		default:
			setInputType(InputType.TYPE_CLASS_TEXT);
		}
		required_ = required;
	}

	public mTextField(Context context, String label, String text, int maxSize, int constraints, int width, int height) {
		super(context);
		bv_ = (BaseView) context;
		this.setLines(5);
		this.setWidth(width);
		// 设置控件字符最大输入量
		this.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxSize) });
		maxSize_ = maxSize;
		this.setFocusable(true);
		this.setText(text);
		
	}
	
	private class TextDefine implements TextWatcher{

		@Override
		public void afterTextChanged(Editable s) {
			
			if (inputType_ == ConfigManager.InputType_NO_CHINESE) {
				boolean result = Pattern.matches("[_A-Za-z\\d]*", s);
				if (!result)
				{
					String s1 = getContentText();
					if (s1 != null && !"".equals(s1))
					{
						s1 = s1.substring(0, s1.length() - 1);
						setText(s1);
//					if (s1.length() > 1)
//					{
//					} else
//					{
//						setText("");
//					}
					}
				}
			}
		
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			
		}
		
	}

	public String getContentText() {
		return super.getText().toString();
	}

	public String getLabel() {
		// TODO Auto-generated method stub
		// 由于国航项目取消了输入框的label。
		// 改为将label作hint显示，嵌入到输入框中，所以作此改动
		String str = "";
		if (null != this.getHint()) {
			str = this.getHint().toString();
			if ((null == str) || (str.equals("")))
				str = "";
		}
		return str;
	}

	protected void onDraw(Canvas canvas) {
		float cImgX = width_ + computeHorizontalScrollOffset();
		if (isComlexbobox_) {
			canvas.drawBitmap(comboboxImg_, cImgX - comboboxImg_.getWidth() - Utils.getSystemScaledValue(8), Utils.getSystemScaledValue(15)+getScrollY(), paint_);
		} else if (isDeletel_&&this.isFocused()&&this.getText().length()>0) {
			if (deletelImg_ == null) {
				deletelImg_ = ConstantRepository.decodeBitmap(bv_.getResources(), R.drawable.edittext_del);
			}
			canvas.drawBitmap(deletelImg_, cImgX-deletelImg_.getWidth() - Utils.getSystemScaledValue(8), Utils.getSystemScaledValue(8)+getScrollY(), paint_);
		}
		try {
			super.onDraw(canvas);
		} catch (java.lang.StackOverflowError se) {
			invalidate();
			se.printStackTrace();
		}
	}
	
    /**
     * 输入框右侧显示一键删除按钮
     * @param isShow
     */
    public void showOneClear(boolean isShow) {
//        if (null == drawable) {
//            drawable = getResources().getDrawable(R.drawable.clear);
//        }
//        if (isShow) {
//            isEnable_ = property_.get("enable");
//            if(isEnable_ != null && "false".equals(isEnable_)){
//                // 这个输入框处于未激活状态。
//                ((MyLPTextFieldView)realView_).setEnabled(false);
//                drawable.setBounds(0, 0, 0, 0);
//                setCompoundDrawables(null, null, null, null);
//            } else {
//                // 设置显示范围,否则不会显示.
//                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                setCompoundDrawables(null, null, drawable, null);
//                setCompoundDrawablePadding(10);
//            }
//        } else {
//            drawable.setBounds(0, 0, 0, 0);
//            setCompoundDrawables(null, null, null, null);
//        }
    }
    
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
//        isEnable_ = property_.get("enable");
//        if(isEnable_ != null && "false".equals(isEnable_)){
//            // 这个输入框处于未激活状态。
//            ((MyLPTextFieldView)realView_).setEnabled(false);
//            drawable.setBounds(0, 0, 0, 0);
//            setCompoundDrawables(null, null, null, null);
//        }
//        super.onWindowFocusChanged(hasWindowFocus);
   }
    
	public boolean onTouchEvent(MotionEvent me) {
		int action = me.getAction();
		int x = (int) me.getX();
		int y = (int) me.getY();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			setFocusableInTouchMode(true);
			if (x > width_ - Utils.getSystemScaledValue(45) && isSearch_){
				//二维码查询输入框的响应事件需要完善(可能响应点击的范围需要稍微调整)
				setFocusableInTouchMode(false);
				BaseView.mid_.alert(bv_, "查询条件不能为空，请输入查询条件！", false);
				return false;
			}
			break;
		case MotionEvent.ACTION_UP:
			if (x > width_ - 30 && !isSearch_) {
				staticTextField_ = this;
				if (isComlexbobox_) {
					return comboboxSelect_.onTouchEvent(me);
				}
			}
		}
		if (!isEnabled()) {
			return true;
		} else {
			return super.onTouchEvent(me);
		}
	}
	
    public void show(){
			Toast.makeText(bv_, "请输入查询条件！", Toast.LENGTH_LONG).show();
    }
    
	public void setContentText(String text) {
		// TODO Auto-generated method stub
		this.setText(text);
	}

	public void shrinkWidth() {
		// TODO Auto-generated method stub

	}

	public void cleanText() {
		// TODO Auto-generated method stub

	}

	public void mould() {
		CssStyle cs = cssStyle_;
		int width = cs != null ? cs.width_ : 0;
		int height = cs != null ? cs.height_ : 0;
		// calculate the width and the height.
		if (cs != null && cs.height_ < 1) {
			height = (int) Math.max(height, getTextSize() * 2 + 5);
		}
		if (cs != null && cs.width_ < 1) {
			TextPaint p = null;
			try {
				p = getPaint();
			} catch (Exception e) {
				p = new TextPaint();
			}
			p.setTextSize(getTextSize());
			BaseView.setTypeFace(p, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
			int textLength = (int) p.measureText(this.getContentText());
			width = (int) Math.max(width, textLength + 50);
		}
		width_ = width;
		height_ = height;
		LinearLayout.LayoutParams lyp = new LinearLayout.LayoutParams(width, height);
		lyp.topMargin = 3;
		setLayoutParams(lyp);
		if (comboboxImg_ == null) {
			comboboxImg_ = ConstantRepository.decodeBitmap(bv_.getResources(), R.drawable.select_arr);
		}
		if (deletelImg_ == null) {
			deletelImg_ = ConstantRepository.decodeBitmap(bv_.getResources(), R.drawable.edittext_del);
		}
		if (paint_ == null) {
			paint_ = new Paint();
		}
	}

	public int getMyInputType() {
		return inputType_;
	}

	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub

	}

	public void setCmpWidth(int width) {

	}

	public void setCssStyle(CssStyle style) {
		cssStyle_ = style;
	}

	public View getCmpView() {
		return this;
	}

	public int getCmpHeight() {
		return height_;
	}

	public int getCmpWidth() {
		return width_;
	}

	public void setInTable(boolean inTable) {
		// TODO Auto-generated method stub
	}

	public boolean isInTable() {
		// TODO Auto-generated method stub
		return false;
	}

	public CssStyle getCssStyle() {
		return cssStyle_;
	}

	boolean tfContentIsChanged_ = false;
	@Override
	protected void onTextChanged(CharSequence text, int start, int before, int after) {
//		if (mask_) {
//			if (after > 1) {
//				tfContentIsChanged_ = false;
//			} else if (!tfContentIsChanged_) {
//				tfContentIsChanged_ = true;
//				if (after == 1) {
//					text = text.subSequence(start, start + 1);
//				} else {
//					text = "";
//				}
//				setText(text.toString());
//			}
//		}
		
		// 输入框联动内容监听
		if (null != isLinked_ && text.length() > 0) {
			// 调用setText()方法会循环递归触发监听器，必须合理退出递归，不然会产生异常。
			Integer integer = Integer.valueOf(text.toString());
			if (text.length() == 1) {
				if (text.charAt(0) == '0' || integer < minValue_) {
					setText("");
					Toast.makeText(bv_, "输入数值不可小于" + minValue_ + "，请重新输入", Toast.LENGTH_SHORT).show();
				} else if (integer > maxValue_) {
					setText("");
					Toast.makeText(bv_, "输入数值不可大于" + maxValue_ + "，请重新输入", Toast.LENGTH_SHORT).show();
				}
			} else {
				if (text.charAt(0) == '0') {
					setText(integer.toString());
					setSelection(integer.toString().length());
				} else if (integer > maxValue_) {
					setText("");
					Toast.makeText(bv_, "输入数值不可大于" + maxValue_ + "，请重新输入", Toast.LENGTH_SHORT).show();
				} else if (integer < minValue_) {
					setText("");
					Toast.makeText(bv_, "输入数值不可小于" + minValue_ + "，请重新输入", Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
		
		if(gainFocus) {
			staticTextField_ = this;
			// 当该域获的焦点后执行该方法
			// 如果tab可见，则点击输入框后将其隐藏。
			Object o = bv_.tabBar_.llH_.getChildAt(0);
			if ((null != o) && (o instanceof TabItem)) {
				TabItem tabItem = (TabItem) o;
				if (tabItem.isShown()) {
					tabItem.setVisibility(View.GONE);
					bv_.statusBar_.setVisibility(View.GONE);
					// ((ImageView) bv_.tabBar_.llH_.getChildAt(bv_.tabBar_.llH_.getChildCount() - 1)).setImageResource(R.drawable.show_btn);
				}
			}
		} else {
//			if (mask_ && tfContentIsChanged_) {
			if (mask_) {
				attrTrueValue_ = getContentText();
			}
		}
		
		super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
	}

	public void releaseResource(View view) {
	}

	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub

	}

	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub
		isEncrypt_ = encrypt;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}
	

}
